<template>
  <div class="BlogTOC-container">
    <h1>目录</h1>
    <RightList :list="list" @select="handSelect" />
  </div>
</template>

<script>
import RightList from "./RightList.vue";
export default {
  props: {
    toc: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      activeAnchor: "", //根据这个变量来突出显示右边的哪个标题
    };
  },
  created(){
    this.$bus.$on("mainScroll",this.setActiveAnchor);
  },
  destroyed(){
    this.$bus.$off("mainScroll",this.setActiveAnchor);
  },
  components: {
    RightList,
  },
  methods: {
    //定位文章的标题
    handSelect(item) {              
      location.hash = item.anchor;
    },
    // 设置页面对应的activeAnchor
    setActiveAnchor(scrollDom){
      if(!scrollDom)
        return;
      //dom距离视口距离来决定activeAnchor
      const range = 20;     //距离200的时候就要被设置成activeAnchor
      for (const dom of this.doms) {
        const top = dom.getBoundingClientRect().top; //距离视口顶边的距离
        if(top >= 0 && top <= range){
          //在规定范围内
          this.activeAnchor = dom.id;
        }
        else if(top > range){
          //在规定范围的下方
          return; //
        }
        else{
          //在规定范围的上方
          this.activeAnchor = dom.id;      //先假设自己是激活的，然后继续看后面的标题是不是也是激活的
        }
      }
    }
  },
  computed: {
    //根据TOC属性得到带有isSelect数组
    list() {
      const newToc = (arr) => {
        return arr.map((item) => ({
          ...item,
          isSelect: this.activeAnchor == item.anchor,
          children: item.children ? newToc(item.children) : undefined, //递归
        }));
      };
      return newToc(this.toc);
    },
    //根据toc得到它们对应的dom数组
    doms() {
      const doms = [];
      const addDoms = (arr) => {
        for (const item of arr) {
          const dom = document.getElementById(item.anchor);
          if(dom)doms.push(dom); //不存在就不要了
          if(item.children) addDoms(item.children);
        }
      };
      addDoms(this.toc);
      return doms;
    },
  }
};
</script>

<style scoped lang="less">
@import "~@/styles/mixin.less";
.BlogTOC-container {
  height: 100%;
  .self-scroll();
  box-sizing: border-box;
  width: 280px;
  padding: 0 10px;
  border-left: 1px solid #ccc;
  &::-webkit-scrollbar {
    display: none;
  }
}
</style>